package com.leetcode.LC;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LC989 {
    public List<Integer> addToArrayForm(int[] A, int K) {

        StringBuilder builder = new StringBuilder("");

        String s1 = "";
        for (int i : A) {
            s1 = s1 + i;
        }
        String s2 = String.valueOf(K);

        int a = s1.length() - 1, b = s2.length() - 1;
        int carry = 0;
        while (a >= 0 || b >= 0) {

            int x = a >= 0 ? s1.charAt(a) - '0' : 0;
            int y = b >= 0 ? s2.charAt(b) - '0' : 0;

            builder.append((x + y + carry) % 10);
            carry = (x + y + carry) / 10;

            a--;
            b--;
        }

        if (carry != 0) {
            builder.append('1');
        }

        String s = builder.reverse().toString();

        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            list.add(s.charAt(i) - '0');
        }
        return list;

    }

    public List<Integer> addToArrayForm2(int[] A, int K) {

        StringBuilder builder = new StringBuilder();
        for (int i : A) {
            builder.append(i);
        }
        String s1 = builder.toString();
        String s2 = String.valueOf(K);
        LinkedList<Integer> list = new LinkedList<>();

        int a = s1.length() - 1, b = s2.length() - 1;
        int carry = 0;
        while (a >= 0 || b >= 0) {

            int x = a >= 0 ? s1.charAt(a) - '0' : 0;
            int y = b >= 0 ? s2.charAt(b) - '0' : 0;

            list.addFirst((x + y + carry) % 10);
            carry = (x + y + carry) / 10;

            a--;
            b--;
        }

        if (carry != 0) {
            list.addFirst(1);
        }

        return list;

    }


    public static void main(String[] args) {
        for (Integer integer : new LC989().addToArrayForm2(new int[]{2, 7, 4}, 181)) {
            System.out.print(integer + ",");
        }
    }
}
